package client

import (
	. "chess_platform/internal/common"
	"chess_platform/models/client"
	"chess_platform/models/h5"
	"chess_platform/models/partner"
	"chess_platform/models/pc"
	"errors"
	"fmt"
)

//[pc]活动
type ActiveController struct {
	GrantController
}

func (b *ActiveController) URLMapping() {
	b.Mapping("ShareAppReward", b.ShareAppReward)
	b.Mapping("ListActivePlayer", b.ListActivePlayer)
}

// @Title 分享app到朋友圈送钻石
// @Description 分享app到朋友圈送钻石
// @Success 0 {string}  状态码
// @router /share-app-reward [post]
func (b *ActiveController) ShareAppReward() {
	//step 1:先获取分布式锁,没有获取到就返回，说明此次已经其它程序已经抢到了锁，正在执行

	//step 2:判断是否已经置位了,如果说置位了说明已经领取过了
	ok, err := client.IsSet(b.Uid, BitShareApp)
	if err != nil {
		LogClient.Error(b.DatabaseError(err.Error()))
		return
	}
	if ok { //今天已经领取过了
		b.Res.Data = map[string]interface{}{
			"reward": 0,
		}
		b.ResponseSuccess("今天分享月友圈已赠送过钻石")
		return
	}
	//step 3:还没领取，置位
	err = client.SetBit(b.Uid, BitShareApp)
	if err != nil {
		LogClient.Error(b.DatabaseError(err.Error()))
		return
	}

	//step 4:赠送用户钻石
	rule, err := h5.RuleByType(RuleActiveShareApp)
	if err != nil {
		LogClient.Error(b.DatabaseError(err.Error()))
		return
	}
	if rule.Amount == 0 {
		LogClient.Debug("分享朋友圈赠送钻石没有设置或奖励设置为0,直接返回,不执行下面派送活动奖励函数")
		return
	}
	err = DeliveryActiveReward(b.Uid, rule.Amount)
	if err != nil {
		LogClient.Error(b.DatabaseError(err.Error()))
		return
	}
	b.Res.Data = map[string]interface{}{
		"reward": rule.Amount,
	}
	b.ResponseSuccess("领取活动奖励成功")
}

// @Title 获取玩家分享而注册的新玩家
// @Description 获取玩家分享而注册的新玩家
// @Param   page_size    body   int     true       "每页显示数量"
// @Param   page_index   body   int     true       "第几页"
// @Success 0 {object} []玩家记录
// @router /list-active-player [post]
func (b *ActiveController) ListActivePlayer() {
	type Params struct {
		ListParams
	}
	var p Params
	if !b.DecodeParams(&p) {
		return
	}
	if !b.ValidParams(&p) {
		return
	}
	ap, count, err := partner.ListAgentPlayerRelation(p.ListParams, b.Uid)
	if err != nil {
		LogPc.Error(b.DatabaseError(err.Error()))
		return
	}
	b.Res.Data = ap
	b.Res.Count = count
	b.ResponseSuccess()
}

//派送活动奖励
func DeliveryActiveReward(uid, diamond int64) error {
	ok := client.ChangeAccountValueFromLobby(uid, diamond, 0, 0, ACCTRAN_OPER_TYPE_Active, 0)
	if !ok {
		LogClient.Error(fmt.Sprintf("游戏服返回失败,赠送活动奖励给玩家:%v失败", uid))
		return errors.New("系统繁忙,请稍后重试")
	}
	err := pc.DoSystemDiamond(SysClientGiveUid, -diamond, uid, SysOpActivity, -1, Player)
	if err != nil {
		LogClient.Error(fmt.Sprintf("从客户端系统赠送帐号:%v扣钻石数:%v到玩家(ID:%v)失败,操作类型为:%v,失败日志:%v",
			SysClientGiveUid, diamond, uid, SysOpActivity, err))
	}
	return nil
}
